import React, { useState, useEffect, useRef, useCallback } from 'react';
import './index.css';
import request from '../../api/axios';
import type { VideoCommentItem } from '../../types';
import Danmaku from './Danmaku';

// 节流函数
const throttle = (func: Function, delay: number) => {
  let timeoutId: number | undefined;
  let lastExecTime = 0;
  return function (this: any, ...args: any[]) {
    const currentTime = Date.now();

    if (currentTime - lastExecTime > delay) {
      func.apply(this, args);
      lastExecTime = currentTime;
    } else {
      clearTimeout(timeoutId);
      timeoutId = window.setTimeout(() => {
        func.apply(this, args);
        lastExecTime = Date.now();
      }, delay - (currentTime - lastExecTime));
    }
  };
};

interface VideoItem {
  id: string;
  title: string;
  author: string;
  avatar: string;
  cover: string;
  videoUrl: string;
  originalUrl: string;
  duration: string;
  likeCount: number;
  commentCount: number;
  shareCount: number;
  isLiked: boolean;
  isFollowed: boolean;
}

// 创建一个全局变量来存储当前视频页面的引用
let videoPageRef: any = null;

// 全局方法：获取当前播放的视频数据
export const getCurrentPlayingVideo = () => {
  if (videoPageRef && videoPageRef.getCurrentPlayingVideo) {
    return videoPageRef.getCurrentPlayingVideo();
  }
  return null;
};

// 全局方法：获取当前播放视频的索引
export const getCurrentVideoIndex = () => {
  if (videoPageRef && videoPageRef.getCurrentVideoIndex) {
    return videoPageRef.getCurrentVideoIndex();
  }
  return 0;
};

// 全局方法：跳转到指定视频
export const scrollToVideo = (index: number) => {
  if (videoPageRef && videoPageRef.scrollToVideo) {
    videoPageRef.scrollToVideo(index);
  }
};

// 全局方法：强制检测当前播放视频
export const forceCheckCurrentVideo = () => {
  if (videoPageRef && videoPageRef.forceCheckCurrentVideo) {
    videoPageRef.forceCheckCurrentVideo();
  }
};

// 全局方法：获取当前视频的评论数据
export const getCurrentVideoComments = () => {
  if (videoPageRef && videoPageRef.getCurrentVideoComments) {
    return videoPageRef.getCurrentVideoComments();
  }
  return [];
};


const VideoPage: React.FC = () => {
  const [activeTab, setActiveTab] = useState('recommend');
  const [currentVideoIndex, setCurrentVideoIndex] = useState(0);
  const [videos, setVideos] = useState<VideoItem[]>([]);
  const [loading, setLoading] = useState(false);
  const videoRefs = useRef<(HTMLVideoElement | null)[]>([]);
  const containerRef = useRef<HTMLDivElement>(null);
  const [tabList, setTabList] = useState([]);

  // 评论相关状态
  const [currentVideoComments, setCurrentVideoComments] = useState<VideoCommentItem[]>([]);
  const [lastVideoId, setLastVideoId] = useState<string | null>(null);

  // 获取当前播放的视频数据
  const getCurrentVideo = useCallback(() => {
    if (videos.length > 0 && currentVideoIndex >= 0 && currentVideoIndex < videos.length) {
      return videos[currentVideoIndex];
    }
    return null;
  }, [videos, currentVideoIndex]);

  // 获取视频评论数据
  const fetchVideoComments = useCallback(async (videoId: string) => {
    if (!videoId || videoId === lastVideoId) {
      return; // 避免重复请求
    }

    try {
      console.log(`正在获取视频 ${videoId} 的评论数据...`);

      const response = await request.get(`/api/health/user/video/v1/findVideoCommentList?videoId=${videoId}`);

      if (response?.data?.result) {
        setCurrentVideoComments(response.data.result);
        setLastVideoId(videoId);
        console.log(`视频 ${videoId} 的评论数据获取成功:`, response.data.result);
      } else {
        console.log(`视频 ${videoId} 暂无评论数据`);
        setCurrentVideoComments([]);
      }
    } catch (error) {
      console.error(`获取视频 ${videoId} 评论数据失败:`, error);
      setCurrentVideoComments([]);
    }
  }, [lastVideoId]);

  // 使用 Intersection Observer 来检测当前可见的视频
  const handleIntersection = useCallback((entries: IntersectionObserverEntry[]) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        const index = parseInt(entry.target.getAttribute('data-index') || '0');
        if (index !== currentVideoIndex) {
          console.log(`滑动检测到视频切换: ${currentVideoIndex} -> ${index}`);
          setCurrentVideoIndex(index);
        }
      }
    });
  }, [currentVideoIndex]);

  // 滚动事件处理函数
  const handleScroll = useCallback(() => {
    if (!containerRef.current) return;

    const container = containerRef.current;
    const scrollTop = container.scrollTop;
    const itemHeight = window.innerHeight - 60; // 减去头部高度
    const newIndex = Math.round(scrollTop / itemHeight);

    if (newIndex !== currentVideoIndex && newIndex >= 0 && newIndex < videos.length) {
      console.log(`滚动检测到视频切换: ${currentVideoIndex} -> ${newIndex}`);
      setCurrentVideoIndex(newIndex);
    }
  }, [currentVideoIndex, videos.length]);

  // 触摸事件处理函数（移动端滑动）
  const handleTouchEnd = useCallback(() => {
    // 延迟执行，等待滑动动画完成
    setTimeout(() => {
      if (!containerRef.current) return;

      const container = containerRef.current;
      const scrollTop = container.scrollTop;
      const itemHeight = window.innerHeight - 60;
      const newIndex = Math.round(scrollTop / itemHeight);

      if (newIndex !== currentVideoIndex && newIndex >= 0 && newIndex < videos.length) {
        console.log(`触摸滑动检测到视频切换: ${currentVideoIndex} -> ${newIndex}`);
        setCurrentVideoIndex(newIndex);
      }
    }, 100);
  }, [currentVideoIndex, videos.length]);

  // 鼠标滚轮事件处理函数（桌面端）
  const handleWheel = useCallback(() => {
    // 延迟执行，等待滚动完成
    setTimeout(() => {
      if (!containerRef.current) return;

      const container = containerRef.current;
      const scrollTop = container.scrollTop;
      const itemHeight = window.innerHeight - 60;
      const newIndex = Math.round(scrollTop / itemHeight);

      if (newIndex !== currentVideoIndex && newIndex >= 0 && newIndex < videos.length) {
        console.log(`滚轮滑动检测到视频切换: ${currentVideoIndex} -> ${newIndex}`);
        setCurrentVideoIndex(newIndex);
      }
    }, 150);
  }, [currentVideoIndex, videos.length]);

  // 键盘事件处理函数（方向键）
  const handleKeyDown = useCallback((event: KeyboardEvent) => {
    if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
      setTimeout(() => {
        if (!containerRef.current) return;

        const container = containerRef.current;
        const scrollTop = container.scrollTop;
        const itemHeight = window.innerHeight - 60;
        const newIndex = Math.round(scrollTop / itemHeight);

        if (newIndex !== currentVideoIndex && newIndex >= 0 && newIndex < videos.length) {
          console.log(`键盘滑动检测到视频切换: ${currentVideoIndex} -> ${newIndex}`);
          setCurrentVideoIndex(newIndex);
        }
      }, 100);
    }
  }, [currentVideoIndex, videos.length]);

  useEffect(() => {
    getTabList();
  }, []);

  const getTabList = async () => {
    const data = await request.get("/api/health/user/video/v1/findVideoCategoryList");
    setTabList(data?.data?.result || []);
    setActiveTab(data?.data?.result[0]?.id);
  };

  // 处理tab切换
  const handleTabChange = (tab: string) => {
    setActiveTab(tab);
    setCurrentVideoIndex(0);
    loadVideosByTab();
  };

  useEffect(() => {
    loadVideosByTab();
  }, [activeTab]);

  // 根据tab加载视频数据
  const loadVideosByTab = async () => {
    setLoading(true);
    const data = await request.get(`/api/health/user/video/v1/findVideoVoList?categoryId=${activeTab}&page=1&count=10`);
    setVideos(data?.data?.result || []);
    setCurrentVideoIndex(0); // 重置到第一个视频
    setLoading(false);
  };

  // 设置滚动监听
  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    // 方法1: 使用 Intersection Observer（主要方法）
    const observer = new IntersectionObserver(handleIntersection, {
      root: container,
      rootMargin: '-50% 0px -50% 0px', // 当视频占据屏幕50%以上时触发
      threshold: 0.5
    });

    // 观察所有视频项
    const videoItems = container.querySelectorAll('.video-item');
    videoItems.forEach((item, index) => {
      item.setAttribute('data-index', index.toString());
      observer.observe(item);
    });

    // 方法2: 添加滚动事件监听（作为补充）
    const throttledScroll = throttle(handleScroll, 100);
    container.addEventListener('scroll', throttledScroll);

    // 方法3: 添加触摸事件监听（移动端支持）
    container.addEventListener('touchend', handleTouchEnd);

    // 方法4: 添加滚轮事件监听（桌面端）
    const throttledWheel = throttle(handleWheel, 200);
    container.addEventListener('wheel', throttledWheel);

    // 方法5: 添加键盘事件监听（方向键）
    document.addEventListener('keydown', handleKeyDown);

    return () => {
      observer.disconnect();
      container.removeEventListener('scroll', throttledScroll);
      container.removeEventListener('touchend', handleTouchEnd);
      container.removeEventListener('wheel', throttledWheel);
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [videos, handleIntersection, handleScroll, handleTouchEnd, handleWheel, handleKeyDown]);

  // 控制视频播放/暂停
  useEffect(() => {
    videoRefs.current.forEach((video, index) => {
      if (video) {
        if (index === currentVideoIndex) {
          video.play().catch(console.error);
        } else {
          video.pause();
        }
      }
    });
  }, [currentVideoIndex]);

  // 调试用：打印当前播放的视频信息
  useEffect(() => {
    const currentVideo = getCurrentVideo();
    if (currentVideo) {
      console.log('当前播放的视频:', currentVideo);

      // 当视频切换时，自动获取评论数据
      if (currentVideo.id && currentVideo.id !== lastVideoId) {
        fetchVideoComments(currentVideo.id);
      }
    }
  }, [getCurrentVideo, fetchVideoComments, lastVideoId]);

  // 添加一个强制检测当前视频的方法
  const forceCheckCurrentVideo = useCallback(() => {
    if (!containerRef.current) return;

    const container = containerRef.current;
    const scrollTop = container.scrollTop;
    const itemHeight = window.innerHeight - 60;
    const newIndex = Math.round(scrollTop / itemHeight);

    if (newIndex !== currentVideoIndex && newIndex >= 0 && newIndex < videos.length) {
      console.log(`强制检测到视频切换: ${currentVideoIndex} -> ${newIndex}`);
      setCurrentVideoIndex(newIndex);
    }
  }, [currentVideoIndex, videos.length]);

  // 定期检查当前视频（作为最后的保障）
  useEffect(() => {
    const interval = setInterval(forceCheckCurrentVideo, 2000);
    return () => clearInterval(interval);
  }, [forceCheckCurrentVideo]);

  // 暴露给外部调用的方法
  const getCurrentPlayingVideo = () => {
    return getCurrentVideo();
  };

  // 获取当前播放视频的索引
  const getCurrentVideoIndex = () => {
    return currentVideoIndex;
  };

  // 跳转到指定视频
  const scrollToVideo = (index: number) => {
    if (index >= 0 && index < videos.length && containerRef.current) {
      const itemHeight = window.innerHeight - 60;
      containerRef.current.scrollTo({
        top: index * itemHeight,
        behavior: 'smooth'
      });
    }
  };

  // 获取当前视频的评论数据
  const getCurrentVideoComments = () => {
    return currentVideoComments;
  };


  // 设置全局引用
  useEffect(() => {
    videoPageRef = {
      getCurrentPlayingVideo,
      getCurrentVideoIndex,
      scrollToVideo,
      forceCheckCurrentVideo,
      getCurrentVideoComments
    };

    return () => {
      videoPageRef = null;
    };
  }, [getCurrentPlayingVideo, getCurrentVideoIndex, scrollToVideo, forceCheckCurrentVideo, getCurrentVideoComments]);

  return (
    <div className="video-page">
      {/* 头部导航 */}
      <header className="video-header">
        <div className="header-tabs">
          {tabList.map((item: any) => (
            <div
              key={item.id}
              className={`tab-item ${activeTab === item.id ? 'active' : ''}`}
              onClick={() => handleTabChange(item.id)}
            >
              {item.name}
            </div>
          ))}
        </div>
      </header>

      {/* 视频列表 */}
      <div
        ref={containerRef}
        className="video-container"
      >
        {loading ? (
          <div className="loading">加载中...</div>
        ) : (
          videos.map((video, index) => (
            <div
              key={video.id}
              className={`video-item ${index === currentVideoIndex ? 'active' : ''}`}
            >
              {/* 视频播放器 */}
              <div className="video-player">
                <video
                  ref={el => { videoRefs.current[index] = el; }}
                  src={video.originalUrl}
                  loop
                  muted
                  autoPlay
                  className="video-element"
                />

                {/* 弹幕组件 */}
                {index === currentVideoIndex && (
                  <Danmaku
                    comments={currentVideoComments}
                  />
                )}
              </div>

              {/* 视频信息显示
              {index === currentVideoIndex && (
                <div className="video-info">
                  <div className="video-title">{video.title}</div>
                  <div className="video-author">
                    <img src={video.avatar} alt={video.author} className="author-avatar" />
                    <span className="author-name">{video.author}</span>
                  </div>
                </div>
              )} */}

              {/* <div className="video-actions">
                <div className="action-item">
                  <button className="action-btn">
                    {video.isLiked ? '❤️' : '🤍'}
                  </button>
                  <span className="action-count">{video.likeCount}</span>
                </div>
                <div className="action-item">
                  <button className="action-btn">💬</button>
                  <span className="action-count">{video.commentCount}</span>
                </div>
                <div className="action-item">
                  <button className="action-btn">📤</button>
                  <span className="action-count">{video.shareCount}</span>
                </div>
              </div> */}
            </div>
          ))
        )}
      </div>
    </div>
  );
};

export default VideoPage;